﻿// Handles notifications of screen resizes
define([   
    'Wjs/ui/elements/notifiers/resizeNotifier'
],
function () {
    'use strict';

    var resizeNotifier = Wjs.getType('resizeNotifier'),
        ResizeHandler = Wjs.defineOnce({

            type: 'ResizeHandler',

            internal: {

                construct: function (cfg, parent) {

                    this.listenOnResize = cfg.listenOnResize || this.listenOnResize;
                    this.onResize = cfg.onResize || this.onResize;

                    if (this.listenOnResize) { // If this view wants to get notified of the window resize

                        resizeNotifier.subscribe(this);
                    }
                },

                listeners: {

                    // Called when the element is about to be destroyed
                    onDestroy: function () {

                        if (this.listenOnResize) {

                            resizeNotifier.unSubscribe(this);
                        }

                        this.listenOnResize = null;
                    }
                }
            },

            // Handles the resize event
            onResize: function () {

                // Notify the mixins interested in handling this event
                this.constructor.notifyMixins('onElementResized', this);

                this.down(function (c) { // Recursively for all the children that have the onResize handler 

                    return c.onResize; 
                })
                .forEach(function (child) {

                    child.onResize(); // Call it
                });
            }
        });

    return ResizeHandler;
});